#!/usr/bin/env python
"""
CFS Web System 健康检查脚本
用于验证系统各个组件是否正常工作
"""

import os
import sys
import django
import requests
import time
from pathlib import Path

# 添加项目路径
sys.path.append(str(Path(__file__).parent.parent))

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cfs_web_system.settings')
django.setup()

from django.core.management import execute_from_command_line
from django.db import connection
from django.contrib.auth.models import User
from apps.core.models import SystemLog, ProcessingTask, Template, UploadedFile

def check_database():
    """检查数据库连接"""
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
            result = cursor.fetchone()
            if result[0] == 1:
                print("✓ 数据库连接正常")
                return True
    except Exception as e:
        print(f"✗ 数据库连接失败: {e}")
        return False

def check_models():
    """检查数据模型"""
    try:
        # 检查用户模型
        user_count = User.objects.count()
        print(f"✓ 用户模型正常 (用户数: {user_count})")
        
        # 检查系统日志模型
        log_count = SystemLog.objects.count()
        print(f"✓ 系统日志模型正常 (日志数: {log_count})")
        
        # 检查任务模型
        task_count = ProcessingTask.objects.count()
        print(f"✓ 任务模型正常 (任务数: {task_count})")
        
        # 检查模板模型
        template_count = Template.objects.count()
        print(f"✓ 模板模型正常 (模板数: {template_count})")
        
        # 检查上传文件模型
        file_count = UploadedFile.objects.count()
        print(f"✓ 上传文件模型正常 (文件数: {file_count})")
        
        return True
    except Exception as e:
        print(f"✗ 数据模型检查失败: {e}")
        return False

def check_static_files():
    """检查静态文件"""
    try:
        static_dirs = [
            'static/css',
            'static/js',
            'static/images',
            'templates'
        ]
        
        for static_dir in static_dirs:
            path = Path(static_dir)
            if path.exists():
                print(f"✓ 静态目录存在: {static_dir}")
            else:
                print(f"⚠ 静态目录不存在: {static_dir}")
        
        return True
    except Exception as e:
        print(f"✗ 静态文件检查失败: {e}")
        return False

def check_log_files():
    """检查日志文件"""
    try:
        log_dirs = [
            'logs',
            '../logs'  # 原始项目的日志目录
        ]
        
        for log_dir in log_dirs:
            path = Path(log_dir)
            if path.exists():
                log_files = list(path.glob('*.log'))
                print(f"✓ 日志目录存在: {log_dir} (文件数: {len(log_files)})")
            else:
                print(f"⚠ 日志目录不存在: {log_dir}")
        
        return True
    except Exception as e:
        print(f"✗ 日志文件检查失败: {e}")
        return False

def check_web_server(url='http://127.0.0.1:8000'):
    """检查Web服务器"""
    try:
        response = requests.get(url, timeout=5)
        if response.status_code == 200:
            print(f"✓ Web服务器正常响应: {url}")
            return True
        else:
            print(f"⚠ Web服务器响应异常: {response.status_code}")
            return False
    except requests.exceptions.ConnectionError:
        print(f"⚠ Web服务器未启动: {url}")
        return False
    except Exception as e:
        print(f"✗ Web服务器检查失败: {e}")
        return False

def check_api_endpoints(base_url='http://127.0.0.1:8000'):
    """检查API端点"""
    try:
        endpoints = [
            '/api/templates/',
            '/api/tasks/',
            '/api/uploaded-files/',
            '/analytics/dashboard/',
            '/analytics/logs/',
        ]
        
        for endpoint in endpoints:
            try:
                response = requests.get(f"{base_url}{endpoint}", timeout=5)
                if response.status_code in [200, 302, 403]:  # 200=OK, 302=重定向, 403=需要登录
                    print(f"✓ API端点正常: {endpoint}")
                else:
                    print(f"⚠ API端点异常: {endpoint} ({response.status_code})")
            except requests.exceptions.ConnectionError:
                print(f"⚠ API端点无法连接: {endpoint}")
        
        return True
    except Exception as e:
        print(f"✗ API端点检查失败: {e}")
        return False

def main():
    """主检查函数"""
    print("="*50)
    print("CFS Web System 健康检查")
    print("="*50)
    
    checks = [
        ("数据库连接", check_database),
        ("数据模型", check_models),
        ("静态文件", check_static_files),
        ("日志文件", check_log_files),
        ("Web服务器", check_web_server),
        ("API端点", check_api_endpoints),
    ]
    
    results = []
    
    for name, check_func in checks:
        print(f"\n检查 {name}...")
        try:
            result = check_func()
            results.append((name, result))
        except Exception as e:
            print(f"✗ {name} 检查出错: {e}")
            results.append((name, False))
    
    # 总结
    print("\n" + "="*50)
    print("检查结果总结:")
    print("="*50)
    
    passed = 0
    total = len(results)
    
    for name, result in results:
        status = "✓ 通过" if result else "✗ 失败"
        print(f"{name}: {status}")
        if result:
            passed += 1
    
    print(f"\n总体状态: {passed}/{total} 项检查通过")
    
    if passed == total:
        print("🎉 系统健康状态良好!")
        return 0
    elif passed >= total * 0.8:
        print("⚠ 系统基本正常，但有部分问题需要关注")
        return 1
    else:
        print("❌ 系统存在严重问题，需要立即处理")
        return 2

if __name__ == '__main__':
    exit_code = main()
    sys.exit(exit_code)